package com.fly.mongodb.service.impl;

import com.fly.mongodb.entity.Person;
import com.fly.mongodb.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /*
        1. 插入文档
        2. 查询文档
        3. 更新文档
        4. 删除文档
     */
    @Override
    public void crudDemo() {
        Person p = new Person("Joe", 34);

        mongoTemplate.insert(p);
        log.info("insert: " + p);

        Person person = mongoTemplate.findById(p.getId(), Person.class);
        log.info("Found: " + person);

        mongoTemplate.updateFirst(Query.query(Criteria.where("name").is("Joe")), Update.update("age", 35), Person.class);
        p = mongoTemplate.findOne(Query.query(Criteria.where("name").is("Joe")), Person.class);
        log.info("Updated: " + p);

        List<Person> people = mongoTemplate.findAll(Person.class);
        log.info("Number of people = :" + people.size());

        mongoTemplate.remove(p);

        mongoTemplate.dropCollection(Person.class);
    }
    
    /*
     c.f.m.service.impl.PersonServiceImpl     : insert: Person [id=6156c2d2b750512a32439ecb, name=Joe, age=34]
     c.f.m.service.impl.PersonServiceImpl     : Found: Person [id=6156c2d2b750512a32439ecb, name=Joe, age=34]
     c.f.m.service.impl.PersonServiceImpl     : Updated: Person [id=6156c2d2b750512a32439ecb, name=Joe, age=35]
     c.f.m.service.impl.PersonServiceImpl     : Number of people = :1
     */
}
